package org.zoomdev.zoom.rpc.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import org.zoomdev.zoom.aop.Interceptor;
import org.zoomdev.zoom.common.Destroyable;
import org.zoomdev.zoom.common.exceptions.ZoomException;
import org.zoomdev.zoom.rpc.utils.RpcUtils;
import org.zoomdev.zoom.serializer.SerializerFactory;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

public final class RpcClient implements Destroyable {

    //rpc等待响应时间
    public static final int WAIT_TIMEOUT_MS = 5000;
    public static final int DEFAULT_HEART_BEAT_MS = 60000;

    private final Map<RpcService, ClientConnection> addressClientConnectionMap = new ConcurrentHashMap<>();
    private final Map<Class<?>, Object> serviceMap = new ConcurrentHashMap<>();

    //交互等待时间
    int timeoutMs = WAIT_TIMEOUT_MS;

    //心跳时间
    private int heartbeatMs = DEFAULT_HEART_BEAT_MS;

    public void setHeartbeatMs(int v) {
        this.heartbeatMs = v;
    }

    RpcClientListener listener;

    ClientContainer clientContainer;


    public RpcClient(SerializerFactory serializerFactory) {
        this.clientContainer = new ClientContainer(serializerFactory);
    }

    NioEventLoopGroup boss;
    Bootstrap bootstrap;

    public void start() {
        if (boss != null) {
            return;
        }

        if (connections.size() == 0) {
            throw new ZoomException("无服务，先使用register方法注册服务");
        }

        boss = new NioEventLoopGroup(1);
        bootstrap = new Bootstrap();
        bootstrap.group(boss)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ClientHandler handler = new ClientHandler(listener);
                        socketChannel.pipeline()
                                .addLast(new IdleStateHandler(0, 0, heartbeatMs,
                                        TimeUnit.MILLISECONDS))
                                .addLast(new ClientIdleHandler())
                                .addLast(new RpcClientMessageToBytesEncoder())
                                .addLast(new RpcClientBytesToMessageDecoder(handler, clientContainer.serializer))
                                .addLast(handler);
                    }
                });
        // ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 8080);
        bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
        bootstrap.option(ChannelOption.TCP_NODELAY, true);
        //bootstrap.option(ChannelOption.SO_TIMEOUT, 5000);

        boss.execute(() -> {
            for (ClientConnection connection : connections) {
                SimpleHandler handler = clientContainer.createHandler(connection, RpcUtils.getHeartbeatMethod());
                connection.setHeartbeatHandler(handler);
                connection.connect();
            }
        });
    }

    public void close() {
        if (boss != null) {
            boss.shutdownGracefully();
            boss = null;
            bootstrap = null;
        }
    }

    @Override
    public void destroy() {
        close();
    }


    public synchronized <T> T register(Class<T> type, List<RpcService> services) {
        //是否存在
        Object oldService = serviceMap.get(type);
        if (oldService != null) {
            throw new ZoomException("服务已经存在，请勿重复注册" + type);
        }

        List<ClientConnection> connections = new ArrayList<>();
        for (RpcService service : services) {
            ClientConnection connection = getConnection(service);
            connections.add(connection);
        }

        Map<String, Handler> handlerMap = new ConcurrentHashMap<>();
        List<Method> methods = RpcUtils.findPublicMethods(type);
        for (Method method : methods) {
            Handler handler = clientContainer.createHandlerWithConnections(method, connections);
            handlerMap.put(method.toGenericString(), handler);
        }

        T result = clientContainer.doRegister(type, handlerMap);
        serviceMap.put(type, result);
        return result;
    }

    public <T> T getService(Class<T> type) {
        return (T) serviceMap.get(type);
    }

    private final List<ClientConnection> connections = new ArrayList<>();

    public ClientConnection getConnection(RpcService service) {
        return addressClientConnectionMap.computeIfAbsent(service, k -> {
            ClientConnection connection = new ClientConnection(k, RpcClient.this, listener);
            connections.add(connection);
            return connection;
        });
    }

    public void setInterceptor(Interceptor interceptor) {
        this.clientContainer.setInterceptor(interceptor);
    }


    public void setListener(RpcClientListener listener) {
        this.listener = listener;
    }


    public void setTimeoutMs(int v) {
        this.timeoutMs = v;
    }
}
